package com.bookshop.order.data;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;

import com.bookshop.book.logic.Book;
import com.bookshop.book.logic.BookManagement;
import com.bookshop.order.logic.Order;
import com.bookshop.pojo.OrderPOJO;
import com.bookshop.promotion.logic.EqualCoupons;
import com.bookshop.tool.Deformat;
import com.bookshop.user.logic.User;
import com.bookshop.user.logic.UserManagement;
import com.bookshop.vo.CustomerVO;
import com.bookshop.vo.OrderVO;
import com.bookshop.vo.OrdersVO;

class PojosToVo {

	static OrdersVO toVO(OrderPOJO[] pojos) {
		OrderVO[] orderVOs = new OrderVO[pojos.length];

		for (int i = 0; i < pojos.length; i++) {
			Order order = toOrder(pojos[i]);
			if (order != null) {
				HashMap<Book, Integer> books = fetchBooks(order.getBooks());

				OrderVO tempOrderVO = new OrderVO();
				tempOrderVO.update(order, books);
				orderVOs[i] = tempOrderVO;
			}
		}

		OrdersVO vo = new OrdersVO();
		vo.update(orderVOs);
		return vo;
	}

	static Order toOrder(OrderPOJO pojo) {
		if (pojo == null) {
			return null;
		}

		String id = pojo.id;
		CustomerVO uservo = new UserManagement().getCustomer(pojo.user);
		User user = uservo.toUser();
		Date date = Deformat.date(pojo.date);
		HashMap<String, Integer> books = Deformat.booksHashMapFromDB(pojo.books);
		EqualCoupons[] equalCoupons = Deformat.euqalCouponsFromDB(pojo.eqivalent);
		double discountCoupons = pojo.discount;
		double price = pojo.price;
		Order order = new Order(id, user, pojo.state,date, books, equalCoupons, discountCoupons, price);
		return order;
	}

	private static HashMap<Book, Integer> fetchBooks(HashMap<String, Integer> pBooks) {
		BookManagement bookManagement = new BookManagement();
		HashMap<Book, Integer> books = new HashMap<>();

		Iterator<String> keyIterator = pBooks.keySet().iterator();
		while (keyIterator.hasNext()) {
			String key = keyIterator.next();
			Book book = bookManagement.searchByID(key);
			int num = pBooks.get(key);
			books.put(book, num);
		}
		return books;
	}

}
